package com.iris.live.services.common;

import java.io.*;

/**
 * Created by huangyongping on 2016/9/2.
 */
public class CloneUtils {

    /**
     * 对象的深度克隆原理：将对象序列化后写在输出流里，因为写在流里面的对象是一份拷贝，原对象仍然在JVM里；
     * 然后再把输出流转换为输入流，把对象反序列化后写出来！这样就实现了对象的深度克隆，克隆后的两个对象完全独立开来，互不影响！
     *
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object deepClone(Object obj) throws IOException, ClassNotFoundException {
        //将对象写到流里
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        //从流里读出来
        oo.writeObject(obj);
        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi = new ObjectInputStream(bi);
        return (oi.readObject());
    }
}
